package com.zhangpingyang.springcloud.hystrixservice.service.impl;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zhangpingyang.springcloud.hystrixservice.domain.CommonResult;
import com.zhangpingyang.springcloud.hystrixservice.domain.User;
import com.zhangpingyang.springcloud.hystrixservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.client.RestTemplate;

/**
 * @Author: Zhang Pingyang
 * @Date: 2019/11/27 17:38
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${service-url.user-service}")
    private String userServiceUrl;

    @Override
    @HystrixCommand(fallbackMethod = "getDefaultUser")
    public CommonResult getUser(Long id) {
        return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id);
    }

    @Override
    @HystrixCommand(fallbackMethod = "getDefaultUser"
    , commandKey = "getUserCommand", groupKey = "getUserGroup", threadPoolKey = "getUserThreadPool")
    public CommonResult getUserCommand(Long id) {

        return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id);
    }

    public CommonResult getDefaultUser(@PathVariable Long id) {
        User defaultUser = new User(-1L, "defaultUser", "123456");
        return new CommonResult(defaultUser);
    }
}
